//
//  WOTimeReportingViewController.m
//
//  Created by Olof Millberg on 2010-04-08.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

// TODO: Changes arent saved

#import "WONewTimeReportViewController.h"
#import "WODatePickerSection.h"
#import "WOTextSection.h"
#import "WOTimeIntervalsSection.h"
#import "DatePickerCell.h"
#import "TextCell.h"
#import "TimePickerCell.h"
#import "AddTimeCell.h"
#import "WOPrototypeAppDelegate.h"

@implementation WONewTimeReportViewController

@synthesize timeReport;

#pragma mark Initialization Methods

- (id) init
{
	if (self = [super initWithStyle:UITableViewStyleGrouped])
		self.title = @"Rapportera Tid";
	return self;
}

- (void) dealloc
{
	[entryDate release];
	[comment release];
	[timeIntervals release];
	[super dealloc];
}

- (void) loadView
{
	[super loadView];
	
	self.tableView.sectionHeaderHeight = 4;
	self.tableView.sectionFooterHeight = 4;
	
	UILabel *titleView = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 200.0f, 30.0f)] autorelease];
	[titleView setBackgroundColor:[UIColor clearColor]];
	[titleView setTextColor:[UIColor whiteColor]];
	[titleView setTextAlignment:UITextAlignmentCenter];
	[titleView setText:@"Rapportera tid"];
	self.navigationItem.titleView = titleView;
	
	if (!timeReport)
	{
		WOTimeInterval *timeInterval = [[WOTimeInterval alloc] init];
		timeInterval.timeType = [workOrder.timeTypes objectAtIndex:0];
		timeInterval.seconds = 7.5*60*60;
		entryDate = [[NSDate date] retain];
		comment = @"";
		timeIntervals = [[NSMutableArray arrayWithObject:timeInterval] retain];
		[timeInterval release];
		
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Klar" 
																				   style:UIBarButtonItemStyleDone 
																				  target:self 
																				  action:@selector(finishTimeReport:)] autorelease];
		editing = YES;
	}
	else 
	{
		entryDate = [timeReport.entryDate copy];
		comment = [timeReport.comment copy];
		timeIntervals = [timeReport.timeIntervals mutableCopy];
		
		self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Ändra" 
																				   style:UIBarButtonItemStylePlain 
																				  target:self 
																				  action:@selector(toggleEditing:)] autorelease];
		editing = NO;
	}
	
	// Sections
	self.sections = [NSMutableArray array];
	[self.sections addObject:[WODatePickerSection datePickerSectionWithTitle:@""]];
	[self.sections addObject:[WOTextSection textSectionWithTitle:@"Anteckning" text:comment]];
	[self.sections addObject:[WOTimeIntervalsSection timeIntervalsSectionWithTitle:@"Tidsintervall"
																			  list:timeIntervals
																		  editable:editing]];
}

#pragma mark -

#pragma mark Table View Methods

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [super tableView:aTableView cellForRowAtIndexPath:indexPath];
	
	//Date picker.
	if ([cell isKindOfClass:[DatePickerCell class]])
	{
		((DatePickerCell*)cell).currentDate = entryDate;
		// TODO: Fix this if the database is improved to support editing of the date.
		// For now we disable the date picker if we're editing an existing time report.
		((DatePickerCell*)cell).enabled = editing && (!timeReport);
		((DatePickerCell*)cell).delegate = self;
	}
	
	//Comment.
	else if ([cell isKindOfClass:[TextCell class]])
	{
		((TextCell*)cell).placeHolder = @"Skriv en kommentar...";
		((TextCell*)cell).title = @"Kommentar";
		((TextCell*)cell).text = comment;
		((TextCell*)cell).editable = editing;
		((TextCell*)cell).viewController = self;
		((TextCell*)cell).delegate = self;
	}
	
	//Time picker.
	else if ([cell isKindOfClass:[TimePickerCell class]])
	{
		WOTimeInterval *timeInterval = [timeIntervals objectAtIndex:indexPath.row];
		
		((TimePickerCell *)cell).timeType = timeInterval.timeType;
		((TimePickerCell *)cell).timeInterval = timeInterval.seconds;
		((TimePickerCell *)cell).timeTypes = workOrder.timeTypes;
		((TimePickerCell *)cell).enabled = editing;
		((TimePickerCell *)cell).tag = indexPath.row;
		((TimePickerCell *)cell).delegate = self;
				
		if ([timeIntervals count] > 1)
			((TimePickerCell *)cell).deleteButton.enabled = YES;
		else
			((TimePickerCell *)cell).deleteButton.enabled = NO;
	}
	
	else if ([cell isKindOfClass:[AddTimeCell class]])
	{
		// Add Time
		[((AddTimeCell*)cell).addTimeButton addTarget:self action:@selector(addTimeInterval:) 
											 forControlEvents:UIControlEventTouchUpInside];
	}
	return cell;
}

#pragma mark -

#pragma mark Misc

- (void)checkTimes
{
	BOOL valid = YES;
	for (WOTimeInterval *ti in timeIntervals)
		valid = valid && (ti.seconds != 0);
	self.navigationItem.rightBarButtonItem.enabled = valid;
}

#pragma mark -

#pragma mark Date

- (void)dateChanged:(NSDate *)newDate
{
	[entryDate release];
	entryDate = [newDate retain];
}

#pragma mark -

#pragma mark Note

- (BOOL)noteView:(WONewNoteViewController*)aNoteView shouldReturnWithText:(NSString *)text
{
	comment = text;
	
	// Set text in the text section to get the correct row height
	for (WOTableSection *section in self.sections)
	{
		if ([section isKindOfClass:[WOTextSection class]])
			((WOTextSection*)section).text = text;
	}
	
	[self.tableView reloadData];
	
	return YES;
}

#pragma mark -

#pragma mark Time Intervals Realted Methods

- (void) addTimeInterval:(id)sender
{
	WOTimeInterval *ti = [[[WOTimeInterval alloc] init] autorelease];
	ti.timeType = [workOrder.timeTypes objectAtIndex:0];
	ti.seconds = 7.5*60*60;
	[timeIntervals addObject:ti];
	
	[self checkTimes];
	[self.tableView reloadData];
}

- (void) timePickerCellDeleteButtonClicked:(TimePickerCell *)timePickerCell
{
	[timeIntervals removeObjectAtIndex:timePickerCell.tag];
	[self checkTimes];
	[self.tableView reloadData];
}

- (void) timePickerCell:(TimePickerCell *)timePickerCell didChangeTimeType:(NSString *)newTimeType
{
	WOTimeInterval *ti = [timeIntervals objectAtIndex:timePickerCell.tag];
	ti.timeType = newTimeType;
}

- (void) timePickerCell:(TimePickerCell *)timePickerCell didChangeTimeInterval:(NSTimeInterval)newTimeInterval
{
	WOTimeInterval *ti = [timeIntervals objectAtIndex:timePickerCell.tag];
	ti.seconds = newTimeInterval;
	[self checkTimes];
}

#pragma mark -

/* A time report is finished */
- (void) finishTimeReport:(id)sender
{	
	if (!timeReport)
	{
		WOPerson *author = ((WOPrototypeAppDelegate *)[[UIApplication sharedApplication] delegate]).currentUser;
		timeReport = [[WOTimeReport alloc] initWithEntryDate:entryDate 
													 comment:comment 
													  author:author
											   timeIntervals:timeIntervals];
		[self.workOrder.timeReports insertObject:timeReport atIndex:0];
		[self.workOrder.addedTimeReports insertObject:timeReport atIndex:0];
	}
	else
	{
		timeReport.entryDate = entryDate;
		timeReport.comment = comment;
		timeReport.timeIntervals = timeIntervals;
		[self.workOrder.updatedTimeReports addObject:timeReport];
	}

	[self.navigationController popViewControllerAnimated:YES];
}

/* Toggle editing */
- (void) toggleEditing:(id)sender
{
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Klar" 
																			   style:UIBarButtonItemStyleDone 
																			  target:self 
																			  action:@selector(finishTimeReport:)] autorelease];
	self.navigationItem.rightBarButtonItem.enabled = NO;
	editing = YES;
	
	for (WOTableSection *section in self.sections)
	{
		if ([section isKindOfClass:[WOTimeIntervalsSection class]])
			[(WOTimeIntervalsSection*)section setEditable:editing];
	}
	
	[self checkTimes];
	[self.tableView reloadData];
}

@end